package org.example.carplatoon.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.example.carplatoon.common.R;
import org.example.carplatoon.dto.employeeDto;
import org.example.carplatoon.entity.employee;
import org.example.carplatoon.service.*;
import org.example.carplatoon.utils.JwtUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RequestMapping
@RestController
public class employeeController {

    @Autowired
    private employeeService employeeService;

    @Autowired
    private carService carService;

    @Autowired
    private carPlatoonService carPlatoonService;

    @Autowired
    private carBindService carBindService;

    @Autowired
    private userService userService;


    /**
     * 管理员登录，返回jwt令牌和相关数据
     *
     * @param e
     * @return
     */
    @PostMapping("/login")
    @Transactional
    public R login(@RequestBody employee e) {

        String password = e.getPassWord();

        if (password.isEmpty() || e.getUserName().isEmpty()) {
            return R.error("用户名或密码错误");
        }

        password = DigestUtils.md5DigestAsHex(password.getBytes());

        LambdaQueryWrapper<employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(employee::getUserName, e.getUserName());
        employee employeeInfo = employeeService.getOne(queryWrapper);

        if (employeeInfo == null) {
            return R.error("未查询到该用户");
        }
        if (!employeeInfo.getPassWord().equals(password)) {
            return R.error("用户名或密码错误");
        }
        if (employeeInfo.getStatus() != 1) {
            return R.error("该账号已被禁用");
        }

        Map<String, Object> tmp = new HashMap<>();
        tmp.put("id", String.valueOf(employeeInfo.getId()));
        tmp.put("userName", employeeInfo.getUserName());
        tmp.put("phoneNum", employeeInfo.getPhoneNum());
        tmp.put("idNumber", employeeInfo.getIdNumber());
        //生成token
        String token = JwtUtils.createToken(tmp);


        employeeDto employeeDto = new employeeDto();
        BeanUtils.copyProperties(employeeInfo, employeeDto);
        employeeDto.setJwt(token);
//        查询正在运行车辆数量
        Integer runningCar = carBindService.sumOfRunningCar();
//        查询正在运行车队数量
        Integer sumOfPlatoon = carPlatoonService.sumOfPlatoon(1);

        Integer sumOfAllCar = carService.sumOfAllCar();

        Integer sumOfUser = userService.sumOfUser();


        employeeDto.setRunningCarTotal(runningCar);
        employeeDto.setPlatoonTotal(sumOfPlatoon);
        employeeDto.setCarTotal(sumOfAllCar);
        employeeDto.setUserTotal(sumOfUser);

        return R.success("登录成功", employeeDto);
    }

    /**
     * 分页查询获取所有管理员信息（可输入userName进行精确查找）
     *
     * @param page
     * @param pageSize
     * @param userName
     * @return
     */
    @GetMapping("/getAllEmployee")
    @Transactional
    public R<Page> getAllEmployee(int page, int pageSize, String userName) {

        Page pageInfo = new Page(page, pageSize);

        LambdaQueryWrapper<employee> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.likeRight(StringUtils.hasText(userName), employee::getUserName, userName);
        queryWrapper.orderByDesc(employee::getUpdateTime);
        employeeService.page(pageInfo, queryWrapper);
        return R.success("success", pageInfo);
    }

    /**
     * 根据请求头Authorization中的token获取管理员信息
     *
     * @param token
     * @return
     */
    @GetMapping("/getEmployeeInfo")
    @Transactional
    public R<employee> getEmployeeInfo(@RequestHeader("Authorization") String token) {
        log.info(token);
        if (!StringUtils.hasText(token)) {
            return R.error("token不存在");
        } else {
            Map<String, Object> employeeInfo = JwtUtils.checkToken(token);
            if (employeeInfo == null) {
                return R.error("token错误");
            }
//            employee e = new employee();
//            e.setUserName((String) employeeInfo.get("userName"));
//            e.setId(Long.valueOf(employeeInfo.get("id").toString()));
//            e.setIdNumber((String) employeeInfo.get("idNumber"));
//            e.setPhoneNum((String) employeeInfo.get("phoneNum"));

            LambdaQueryWrapper<employee> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(employee::getId, employeeInfo.get("id"));
//                    .eq(employee::getUserName, employeeInfo.get("userName"))
//                    .eq(employee::getIdNumber, employeeInfo.get("idNumber"))
//                    .eq(employee::getPhoneNum, employeeInfo.get("phoneNum"));
            employee e = employeeService.getOne(queryWrapper);

            return R.success("获取数据成功", e);
        }
    }

    @PostMapping("/addEmployee")
    @Transactional
    public R<String> getaddEmployee(@RequestBody employee emp) {
        String userName = emp.getUserName();
        LambdaQueryWrapper<employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(employee::getUserName, userName)
                .or()
                .eq(employee::getPhoneNum,emp.getPhoneNum())
                .or()
                .eq(employee::getIdNumber,emp.getIdNumber());

        int count = employeeService.count(queryWrapper);
        if (count > 0) {
            return R.error("该用户名或手机号或身份证号码已存在");
        }
        String phoneNum = emp.getPhoneNum();
        String idNUmber = emp.getIdNumber();
        if (phoneNum.length() != 11 || idNUmber.length() != 18) {
            return R.error("请输入正确的手机号或身份证号码");
        }
        String passWord = emp.getPassWord();
        passWord = DigestUtils.md5DigestAsHex(passWord.getBytes());
        emp.setPassWord(passWord);
        emp.setStatus(1);
//        todo:暂时将头像src设置为固定值
        emp.setAvatar("/images/test.jpg");
        employeeService.save(emp);
        return R.success("创建成功", null);
    }

    @PostMapping("/changeEmployee")
    @Transactional
    public R<String> getchangeEmployee(@RequestBody employee emp1) {

        Long id = emp1.getId();
        LambdaQueryWrapper<employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(employee::getId, id);
        int count = employeeService.count(queryWrapper);
        if (count == 0) {
            return R.error("该管理员信息不存在");
        }
        queryWrapper.clear();
        queryWrapper.ne(employee::getId, id)
                .and(i -> i.eq(employee::getUserName,emp1.getUserName())
                        .or().eq(employee::getPhoneNum, emp1.getPhoneNum())
                        .or().eq(employee::getIdNumber, emp1.getIdNumber()));
        count = employeeService.count(queryWrapper);
        if (count > 0) {
            return R.error("用户名或手机号或身份证号已存在");
        }
        String phoneNum = emp1.getPhoneNum();
        String idNUmber = emp1.getIdNumber();
        if (phoneNum.length() != 11 || idNUmber.length() != 18) {
            return R.error("请输入正确的手机号或身份证号码");
        }
        employeeService.updateById(emp1);
        return R.success("更新成功", null);
    }

    @GetMapping("/getInfo")
    @Transactional
    public R<employeeDto> getInfo() {
        employeeDto employeeDto = new employeeDto();
//        查询正在运行车辆数量
        Integer runningCar = carBindService.sumOfRunningCar();
//        查询正在运行车队数量
        Integer sumOfPlatoon = carPlatoonService.sumOfPlatoon(1);

        Integer sumOfAllCar = carService.sumOfAllCar();

        Integer sumOfUser = userService.sumOfUser();


        employeeDto.setRunningCarTotal(runningCar);
        employeeDto.setPlatoonTotal(sumOfPlatoon);
        employeeDto.setCarTotal(sumOfAllCar);
        employeeDto.setUserTotal(sumOfUser);

        return R.success("信息获取成功", employeeDto);
    }

}
